#!/usr/bin/env python

import sys
import gtk
import gobject
import GuiLoader
import ModelLoader
from ModelLoader import AvatarItem



# currently unused
#class CellRendererAvatarItem(gtk.GenericCellRenderer):
#    __gproperties__ = {
#        "avatar-item": 
#            (gobject.TYPE_OBJECT, "AvatarItem", 
#                "AvatarItem", gobject.PARAM_READWRITE),
#    }
#
#    def __init__(self):
#        self.__gobject_init__()
#
#    def do_set_property(self, pspec, value):
#        setattr(self, pspec.name, value)
#
#    def do_get_property(self, pspec):
#        return getattr(self, pspec.name)
#
#    def on_render(self, window, widget, bgarea, cellarea, exposearea, flags):
#        item = getattr(self, "avatar-item")
#
#        textrender = gtk.CellRendererText()
#        iconrender = gtk.CellRendererPixbuf()
#
#        width = 50
#        height = 100
#        iconbuf = gtk.gdk.pixbuf_new_from_file_at_size(item.icon, width, height)
#        
#        iconrender.set_property ('xalign', 0) # left justify
#        iconrender.set_property ('pixbuf', iconbuf)
#        textrender.set_property ('markup', item.get_markup())
#
#        iconsize = iconrender.get_size(widget, cellarea)
#        textsize = textrender.get_size(widget, cellarea)
#        iconarea = CellRendererAvatarItem._get_icon_area(cellarea, iconsize, textsize)
#        textarea = CellRendererAvatarItem._get_text_area(cellarea, iconsize, textsize)
#        
#        iconrender.render(window, widget, bgarea, iconarea, exposearea, flags)
#        textrender.render(window, widget, bgarea, textarea, exposearea, flags)
#
#    def on_get_size(self, widget, cellarea=None):
#        item = getattr(self, "avatar-item")
#
#        textrender = gtk.CellRendererText()
#        iconrender = gtk.CellRendererPixbuf()
#
#        width = 100
#        height = 200
#        iconbuf = gtk.gdk.pixbuf_new_from_file_at_size(item.icon, width, height)
#        
#        iconrender.set_property ('pixbuf', iconbuf)
#        textrender.set_property ('markup', item.get_markup())
#
#        return CellRendererAvatarItem._get_total_size(
#                iconrender.get_size(widget, cellarea), 
#                textrender.get_size(widget, cellarea))
#
#    # NOTE: size => 0:x, 1:y, 2:width, 3:height
#    @staticmethod
#    def _print_area(area):
#        print area.x, area.y, area.width, area.height
#
#    @staticmethod
#    def _get_total_size(iconsize, textsize):
#        (iconx, icony, iconw, iconh) = iconsize
#        (textx, texty, textw, texth) = textsize
#        return (min(iconx, textx), 
#                min(icony, texty), 
#                iconw + textx + textw, 
#                max(iconh, texty + texth))
#
#    @staticmethod
#    def _get_icon_area(area, iconsize, textsize):
#        iconarea = gtk.gdk.Rectangle()
#        iconarea.x = area[0] + iconsize[0]
#        iconarea.y = area[1] + iconsize[1]
#        iconarea.width = iconsize[2]
#        iconarea.height = iconsize[3]
#        return iconarea
#
#    @staticmethod
#    def _get_text_area(area, iconsize, textsize):
#        textarea = gtk.gdk.Rectangle()
#        textarea.x = area[0] + textsize[0] + iconsize[2]
#        textarea.y = area[1] + textsize[1]
#        textarea.width = textsize[2]
#        textarea.height = textsize[3]
#        return textarea
#
#
#gobject.type_register(CellRendererAvatarItem)

class PortError(object):
    pass


class PortWindow(object):
    # destroy handler
    def on_window_destroy(self, widget, data=None):
        gtk.main_quit()

    # when the user requests a destroy
    def on_window_delete_event(self, widget, event, data=None):
        return False # Propogate event

class PortAvatarSelectUI(PortWindow):
    def __init__ (self, manager, guifile):
        GuiLoader.connect(self, guifile)

        self.manager = manager
        self.selected = None
        self.select = GuiLoader.get_object("AvatarSelectWindow")
        self.edit = GuiLoader.get_object("AvatarEditDialog")
        self.view = GuiLoader.get_object("AvatarTreeView")
        self.store = gtk.ListStore(str)
        
        self.__setup_tree_view()

    def __setup_tree_view(self):
        cell = gtk.CellRendererText()
        col = gtk.TreeViewColumn()
        col.pack_start(cell, True)
        col.add_attribute(cell, 'markup', 0)

        self.view.append_column(col)
        self.view.set_model(self.store)

    def set_model(self, avatars):
        self.store.clear()
        for text in [avatar.get_markup() for avatar in avatars]:
            self.store.append([text])
    
    def get_selection(self):
        (model, iter) = self.view.get_selection().get_selected()
        if iter == None:
            raise PortError
        
        return AvatarItem(self.store.get_value(iter, 0))

    def have_selection(self):
        (model, iter) = self.view.get_selection().get_selected()
        return False if iter == None else True

    def prompt_user(self, navatars):
        if navatars == 1: 
            self.manager.on_avatar_default()
            return False

        self.select.show_all()
        if navatars == 0:
            self.edit.show_all()
        return True # must wait for user

    def on_AvatarSelectButton_clicked(self, data=None):
        if not self.have_selection():
            return

        self.select.hide_all()
        self.edit.hide_all()
        self.manager.on_avatar_selected()

    def on_AvatarAddButton_clicked(self, data=None):
        pass

    def on_AvatarDeleteButton_clicked(self, data=None):
        pass

    def on_AvatarEditButton_clicked(self, data=None):
        self.edit.show_all()

    def on_AvatarSaveButton_clicked(self, data=None):
        self.edit.hide_all()

    def on_AvatarEditCloseButton_clicked(self, data=None):
        self.edit.hide_all()

class PortAvatarSelectModel(object):
    def __init__ (self, manager, avatarfile):
        self.manager = manager
        self.avatars = []
        ModelLoader.load_avatars(avatarfile, self.avatars)
        

class PortAvatarManager(object):
    def __init__ (self, avatarfile=None, guifile=None):
        
        if avatarfile == None: avatarfile = 'avatars.db'
        if guifile == None: guifile = '../../share/glade/gui-avatar-select.xml'
        
        self.current = None
        self.model = PortAvatarSelectModel(self, avatarfile)
        
        self.ui = PortAvatarSelectUI(self, guifile)
        self.ui.set_model(self.model.avatars)
        self.ui.prompt_user(len(self.model.avatars))

    def on_avatar_selected(self):
        self.current = self.ui.get_selection()

    def on_avatar_default(self):
        self.current = self.avatars[0]


class PortApp(object):
    
    def __init__ (self):
        self.select = PortAvatarManager()

    # destroy handler
    def on_window_destroy(self, widget, data=None):
        PortController.shutdown()

    # when the user requests a destroy
    def on_window_delete_event(self, widget, event, data=None):
        return False # Propogate event


if __name__ == "__main__":
    app = PortApp()
    gtk.main()

